// 施工配合模块
<template>
  <el-row :gutter="6">
    <myAnnounceDlg @operationSucc="operationState($event)" :configs="myAnnounceDlgConfig"></myAnnounceDlg>
    <el-col :span="24" class="col-flex">
      <el-col class="breadcrumb-container">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/technical'}">技术服务</el-breadcrumb-item>
          <el-breadcrumb-item>施工配合</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
      <!-- 主要操作区域 -->
      <el-col v-loading="config.loading" class="maincont-container">
        <div class="table-container" v-if="config.tableShow">
          <my-tableX
            :configs="completedTaskConfig.configs"
            :tableData="completedTaskConfig.data"
            @dataEdit="handleTodo"
            @dataAdd="addNewApply"
            @dataView="viewDetail"
            @dataDelete="deleteData"
          ></my-tableX>
        </div>
        <div class="flow-container" v-if="!config.tableShow">
          <div class="flow-form scrollable">
            <el-form
              ref="flowFormData"
              :validate-on-rule-change="false"
              :model="flowFormData"
              label-width="0px"
              size="small"
              :rules="flowConfig.currentRule"
            >
              <h4 class="form-title">{{flowConfig.formTitle}}</h4>
              <table border="1px" cellpadding="0" cellspacing="0" class="form-data">
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">勘察标段</td>
                  <td colspan="8" width="80%">
                    <el-input readonly type="text" size="small" v-model="flowFormData.tenders"></el-input>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">主题内容</td>
                  <td colspan="3" width="30%">
                    <el-form-item label-width="0" :show-message="true" prop="thematicContent">
                      <el-input
                        :readonly="flowConfig.formState.readonly"
                        type="text"
                        size="small"
                        v-model="flowFormData.thematicContent"
                      ></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">参加人</td>
                  <td colspan="3" width="30%">
                    <el-form-item label-width="0" :show-message="true" prop="participant">
                      <el-input
                        :readonly="flowConfig.formState.readonly"
                        type="text"
                        size="small"
                        v-model="flowFormData.participant"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">时间</td>
                  <td colspan="3" width="30%">
                    <el-form-item label-width="0" :show-message="true" prop="date">
                      <el-date-picker
                        :readonly="flowConfig.formState.readonly"
                        v-model="flowFormData.date"
                        type="date"
                        placeholder="选择日期"
                        value-format="yyyy-MM-dd"
                        style="width:100%"
                        :picker-options="pickerOptions"
                      ></el-date-picker>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">地点</td>
                  <td colspan="3" width="30%">
                    <el-form-item label-width="0" :show-message="true" prop="address">
                      <el-input
                        size="small"
                        v-model="flowFormData.address"
                        :readonly="flowConfig.formState.readonly"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">主要结论</td>
                  <td class="form-label" colspan="8" width="80%">
                    <el-form-item label-width="0" :show-message="true" prop="mainConclusions">
                      <el-input
                        v-model="flowFormData.mainConclusions"
                        type="textarea"
                        rows="5"
                        size="small"
                        :readonly="flowConfig.formState.readonly"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>
                <!-- <tr align="center">
                  <td class="form-label" colspan="2" width="20%">现场照片</td>
                  <td align="left" class="form-label" colspan="8" width="80%">
                    <el-upload
                      :http-request="uploadSectionFileImages"
                      :file-list="fileListImage"
                      :before-upload="beforeUpload"
                      :on-exceed="handleExceed"
                      multiple
                      :limit="5"
                      :accept="filetype"
                      :disabled="flowConfig.formState.readonly"
                      list-type="picture-card"
                      :on-preview="handlePictureCardPreviewImage"
                      :on-remove="imageHandleRemove"
                    >
                      <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="imageDialogVisible">
                      <img width="100%" :src="imageDialogImageUrl" alt />
                    </el-dialog>
                  </td>
                </tr>-->
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">附件：会议纪要</td>
                  <td align="left" class="form-label" colspan="8" width="80%">
                    <el-upload
                      action="#"
                      :http-request="uploadSectionFileSuggestion"
                      :file-list="fileList"
                      :before-upload="beforeUpload"
                      :on-exceed="handleExceed"
                      multiple
                      :limit="5"
                      :accept="filetype"
                      :disabled="flowConfig.formState.readonly"
                      list-type="picture-card"
                      :on-preview="handlePictureCardPreviewSuggestion"
                      :on-remove="suggestionHandleRemove"
                      :before-remove="beforeRemove"
                    >
                      <i class="el-icon-plus"></i>
                    </el-upload>
                    <!-- <el-dialog :visible.sync="suggestionDialogVisible">
                      <img width="100%" :src="suggestionDialogImageUrl" alt />
                    </el-dialog>-->
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">各方补充意见</td>
                  <td class="form-label" colspan="8" width="80%">
                    <el-input
                      v-model="flowFormData.supplementaryOpinions"
                      type="textarea"
                      rows="5"
                      size="small"
                      :readonly="flowConfig.formState.readonly"
                    ></el-input>
                  </td>
                </tr>
              </table>
              <el-form-item class="btns">
                <el-button
                  v-if="!flowConfig.formState.readonly"
                  @click="resolveflow"
                  type="primary"
                >{{flowConfig.currentBtn.resolveText}}</el-button>
                <el-button @click="cancelflow">{{flowConfig.currentBtn.cancelText}}</el-button>
              </el-form-item>
            </el-form>
          </div>
          <myExportTableBtn :configs="exportTableConfig"></myExportTableBtn>
        </div>
      </el-col>
    </el-col>
  </el-row>
</template>


<script>
import myTableX from "@/components/base/tableX";
import { formatDate } from "@/utils/date";
import httpfile from "@/api/file/index";
import fileType from "@/config/file.type.config";
import myAnnounceDlg from "@/components/base/announceDlg";
import myExportTableBtn from "@/components/base/exportTableBtn";
// 全局变量
var glbVar = {};
var taskListParam = {};

export default {
  inject: ["reload"],
  components: {
    myTableX,
    myAnnounceDlg,
    myExportTableBtn,
  },

  // 初始化
  created() {
    console.log("create 刷新了");

    glbVar.subjectId = this.$store.state.projectInfo.projectName;
    glbVar.user = this.$store.state.m_user.userInfo;
    this.flowFormData.subjectId = glbVar.subjectId;

    this.$store.state.m_user.roles.forEach((item) => {
      if (item.id < 4 || item.id > 7) {
        this.myAnnounceDlgConfig.announceInfo.role.push(item.id);
      }
    });

    // 初始化工程数据列表
    this.$api.project
      .listByCompany(glbVar.subjectId, glbVar.user.company)
      .then((res) => {
        console.log(res);
        if (res.code === 200) {
          this.dictData.prolist = res.data;
        }
      });

    //操作权限
    if (glbVar.user.roleId <= 3 || glbVar.user.roleId >= 8) {
      this.completedTaskConfig.configs.operationBtn.add = false;
      this.completedTaskConfig.configs.operationCol.edit = false;
      this.completedTaskConfig.configs.operationCol.delete = false;
    }

    let query = this.$route.query;

    if (Object.keys(query).length != 0) {
      this.config.tableShow = false;
      this.$api.constrcooperation
        .getonly({ id: query.remark })
        .then((res) => {
          if (res.code === 200) {
            this.viewDetail(res.data);
          } else {
            console.log("get todo business detail:" + res.msg);
          }
        })
        .catch((err) => {
          console.log("get todo business detail:" + err);
          this.$message.info("get todo business detail:" + err);
        });
    }
  },

  mounted() {
    console.log("mount 刷新了");

    console.log();

    taskListParam = {
      projectId: glbVar.subjectId,
      userId: glbVar.user.id,
    };

    this.initList(taskListParam);

    //文件导出 是否可见
    this.exportTableConfig.isshown = this.flowConfig.formState.readonly;
    this.exportTableConfig.subjectId = glbVar.subjectId;
  },

  watch: {
    $route(to, from) {
      if (to.path === from.path && to.query !== from.query) {
        this.initList(taskListParam);
      }
    },
    //文件导出 是否可见 监听变化
    "flowConfig.formState.readonly"(newstate, old) {
      this.exportTableConfig.isshown = this.flowConfig.formState.readonly;
    },
  },

  data() {
    let glbcolumns = [
      { field: "tenders", name: "勘察标段" },
      { field: "thematicContent", name: "主题内容" },
      { field: "date", name: "时间" },
      { field: "address", name: "地点" },
    ];
    return {
      //上传完成限制
      isUploadFinished: false,
      fileListLength: 0,

      // 时间选择器逻辑
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > Date.now();
        },
      },

      filetype: fileType.Announce,
      //文件列表
      //   fileListImage: [],
      //   fileListImage4api: [],
      //   imageDialogVisible: false,
      //   imageDialogImageUrl: "",

      fileList: [],
      fileListSuggestion4api: [],
      //suggestionDialogVisible: false,
      suggestionDialogImageUrl: "",

      isupdate: false,
      iscreate: true,

      showDlg: true,

      //导出按钮Config
      exportTableConfig: {
        isshown: false,
        subjectId: glbVar.subjectId,
        model: 103,
        flowFormData: {},
      },

      config: {
        tableShow: true,
        todoCount: 0,
        loading: false,
      },
      myAnnounceDlgConfig: {
        dialogFormVisible: false,
        isupdate: false,
        announceInfo: {
          remark: "",
          subject_id: "",
          url: "",
          notice_type: "施工配合",
          role: [],
          create_by: "",
          create_time: "",
          notice_content: "",
          notice_title: "",
          path: "",
          remark: "",
        },
      },

      completedTaskConfig: {
        configs: {
          nodata: "暂无施工配合发文",
          columns: glbcolumns,
          showFilterRow: {
            show: true,
          },
          operationBtn: {
            show: true,
            add: true,
          },
          operationCol: {
            show: true,
            view: true,
            edit: true,
            delete: true,
            options: {
              view: {
                text: "详情",
              },
            },
          },
        },
        data: [],
      },

      flowConfig: {
        formTitle: "施工配合上传",
        currentRule: {
          thematicContent: [{ required: true, trigger: "blur" }],
          participant: [{ required: true, trigger: "blur" }],
          date: [{ required: true, trigger: "blur" }],
          address: [{ required: true, trigger: "blur" }],
          mainConclusions: [{ required: true, trigger: "blur" }],
        },
        currentBtn: {
          resolveText: "提交",
          cancelText: "返回",
        },
        formState: {
          readonly: false,
        },
      },

      // 数据字典数据
      dictData: {
        //工程列表
        prolist: [],
      },

      currRecordTime: "",

      flowFormData: {},
    };
  },

  methods: {
    //监听上传公告结果
    operationState(msg) {
      console.log(msg);
      if (msg) {
        this.$message.success("发布成功");
        this.config.tableShow = true;
      } else {
        this.$message.error("发布失败");
      }
      this.initList(taskListParam);
      this.config.loading = false;
    },

    initList(taskListParam) {
      console.log(glbVar.user.nick_name + "/" + glbVar.user.company);

      let tender = "";
      if (glbVar.user.roleId > 3 && glbVar.user.roleId < 8) {
        tender = glbVar.user.nick_name + "/" + glbVar.user.company;
      } else {
        tender = null;
      }
      // 初始化列表
      this.$api.constrcooperation
        .getlist({
          subjectId: glbVar.subjectId,
          tenders: tender,
        })
        .then((res) => {
          if (res.code === 200) {
            this.completedTaskConfig.data = res.data;
          } else {
            console.log("get finished business detail:" + res.msg);
          }
        })
        .catch((err) => {
          console.log("get finished business detail:" + err);
          this.$message.info("get finished business detail:" + err);
        });
    },

    /**
     * @description: 发起一个变更申请,预操作
     */
    addNewApply() {
      this.flowConfig.formState.readonly = false;
      this.config.tableShow = false;
      this.flowFormData = {};
      this.flowFormData.tenders =
        glbVar.user.nick_name + "/" + glbVar.user.company;
      this.flowFormData.subjectId = glbVar.subjectId;
      this.flowFormData.createTime = formatDate(
        new Date(),
        "yyyy-MM-dd hh:mm:ss"
      );

      this.iscreate = true;
      this.isupdate = false;
      this.flowConfig.currentBtn.resolveText = "上传";
      //   this.fileListImage = [];
      //   this.fileListImage4api = [];
      this.fileList = [];
      this.fileListSuggestion4api = [];
    },

    /**
     * @description: 处理待办任务
     */
    handleTodo(row) {
      // this.currRecordTime = row.recordingDate;
      let id = row.id;
      this.flowFormData = row;
      // this.initComments(id);
      //   this.fileListImage = [];
      //   this.fileListImage4api = [];
      this.fileList = [];
      this.fileListSuggestion4api = [];
      console.log(row);

      if (row.url != "") {
        row.url.split(";").forEach((item) => {
          if (item != "") {
            let b = item.split("/");
            this.fileList.push({
              name: b.slice(b.length - 1, b.length).toString(String),
              url: item,
            });

            this.fileListSuggestion4api.push({
              name: b.slice(b.length - 1, b.length).toString(String),
              url: item,
            });
          }
        });
      }

      this.flowConfig.formState.readonly = false;
      this.config.tableShow = false;

      this.isupdate = true;
      this.iscreate = false;
      this.flowConfig.currentBtn.resolveText = "修改";
    },

    // 查看流程运行详情,运行时
    viewDetail(row) {
      // console.log(row);
      let id = row.id;
      this.flowFormData = row;
      // this.initComments(id);
      //   this.fileListImage = [];
      //   this.fileListImage4api = [];
      this.fileList = [];
      this.fileListSuggestion4api = [];
      console.log(row);

      if (row.url != "") {
        row.url.split(";").forEach((item) => {
          if (item != "") {
            let b = item.split("/");
            this.fileList.push({
              name: b.slice(b.length - 1, b.length).toString(String),
              url: item,
            });

            this.fileListSuggestion4api.push({
              name: b.slice(b.length - 1, b.length).toString(String),
              url: item,
            });
          }
        });
      }
      this.flowConfig.formState.readonly = true;
      this.config.tableShow = false;
      this.isupdate = false;
      this.iscreate = false;
    },

    // 删除数据
    deleteData(row) {
      this.$confirm("此操作将永久删除该公告, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.listloading = true;
        this.$api.constrcooperation
          .delete({
            id: row.id,
            path: this.$route.path,
            subject_id: glbVar.subjectId,
          })
          .then((res) => {
            if (res.code == 200) {
              console.log(res);
              this.$message.success("删除成功");
              this.config.tableShow = true;
              this.initList(taskListParam);
              //   this.$api.announce
              //     .deleteRoleByNotice({ reqMap: row.notice_id })
              //     .then(res => {
              //       this.listloading = false;
              //       if (res.code === 200) {
              //         this.$message.success("删除成功");
              //         this.reload();
              //       } else {
              //         this.$message.error("删除失败:" + res.msg);
              //       }
              //     })
              //     .catch(err => {
              //       this.$message.error("删除失败:" + err);
              //     });
              // } else {
              //   this.listloading = false;
              //   this.$message.error("删除失败:" + res.msg);
            }
          })
          .catch((err) => {
            this.listloading = false;
            this.$message.error("删除失败11:" + err);
          });
      });
    },

    // 执行流程
    resolveflow() {
      if (!this.isUploadFinished) {
        console.log("return UploadFinished");
        this.$message.warning("文件未上传完毕，请稍后重试！");
        return;
      }
      // 预验证
      this.$refs.flowFormData.validate((res) => {
        if (res) {
          this.$confirm("提交操作后不可更改，是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.handleResolve();
            })
            .catch(() => {
              return;
            });
        } else {
          this.$message.warning("请检查必填项");
        }
      });
    },

    handleResolve() {
      console.log("我是具体工作量");
      this.flowFormData.url = this.fileListSuggestion4api
        .map((item) => {
          return (
            "/" +
            this.$store.state.projectInfo.projectName +
            "/施工配合/" +
            item.name
          );
        })
        .join(";");
      console.log("我是data");
      console.log(this.flowFormData);

      if (this.isupdate) {
        this.$api.constrcooperation
          .modify(this.flowFormData)
          .then((res) => {
            if (res.code === 200) {
              //修改公告
              //获取公告id
              this.$api.announce
                .getnoticebypath({
                  path: this.$route.path,
                  remark: this.flowFormData.id,
                  subject_id: glbVar.subjectId,
                })
                .then((res) => {
                  if (res.code == 200) {
                    console.log(res.data);
                    this.myAnnounceDlgConfig.isupdate = true;
                    this.myAnnounceDlgConfig.announceInfo = res.data;
                    this.myAnnounceDlgConfig.announceInfo.notice_content = this.flowFormData.mainConclusions;
                    this.myAnnounceDlgConfig.announceInfo.notice_title = this.flowFormData.thematicContent;
                    this.myAnnounceDlgConfig.dialogFormVisible = true;
                  } else {
                    this.$message.error("操作失败!" + res.msg);
                  }
                })
                .catch((err) => {
                  this.config.loading = false;
                  this.$message.error("操作失败!" + err);
                });
            } else {
              this.config.loading = false;
              this.$message.error("提交表单失败:" + res.msg);
            }
          })
          .catch((err) => {
            this.config.loading = false;
            this.$message.error("提交表单失败:" + err);
          });
      } else {
        this.$api.constrcooperation
          .add(this.flowFormData)
          .then((res) => {
            console.log("add constrcooperation res");
            console.log(res);
            if (res.code === 200) {
              //添加公告
              this.myAnnounceDlgConfig.isupdate = false;
              this.myAnnounceDlgConfig.announceInfo.notice_title = this.flowFormData.thematicContent;
              this.myAnnounceDlgConfig.announceInfo.url = this.flowFormData.url;
              this.myAnnounceDlgConfig.announceInfo.remark = res.data.id;
              this.myAnnounceDlgConfig.announceInfo.subject_id =
                glbVar.subjectId;
              this.myAnnounceDlgConfig.announceInfo.notice_content = this.flowFormData.mainConclusions;
              this.myAnnounceDlgConfig.dialogFormVisible = true;

              // this.$api.announce
              //   .add(this.flowAnnouceData)
              //   .then(res => {
              //     this.config.loading = false;
              //     if (res.code == 200) {

              //     } else {
              //       this.$message.error("操作失败!" + res.msg);
              //     }
              //   })
              //   .catch(err => {
              //     this.config.loading = false;
              //     this.$message.error("操作失败!" + err);
              //   });
            } else {
              this.config.loading = false;
              this.$message.error("提交表单失败:" + res.msg);
            }
          })
          .catch((err) => {
            this.config.loading = false;
            this.$message.error("提交表单失败:" + err);
          });
      }
    },

    // 取消流程
    cancelflow() {
      this.config.tableShow = true;
      this.flowFormData = {};
    },

    //文件上传
    submitUpload() {
      this.$refs.upload.submit();
    },

    suggestionHandleRemove(file, fileList) {
      this.fileList = fileList;

      let num = this.fileListSuggestion4api.indexOf(file.url);
      this.fileListSuggestion4api.splice(num, 1);

      this.fileListLength -= 1;
    },

    // handlePictureCardPreviewImage(file) {
    //   console.log(file);
    //   this.imageDialogVisible = true;
    //   this.imageDialogImageUrl = file.url;
    // },
    handlePictureCardPreviewSuggestion(file) {
      console.log(file);
      window.open(file.url);
      // if (this.iscreate) {
      //   window.open("http://39.106.121.254:5031/" + file.url);
      // } else {
      //   window.open(file.url);
      // }
    },

    beforeUpload(file) {
      let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (this.filetype.indexOf("." + testmsg.toLowerCase()) < 0) {
        this.$message({
          message: "上传文件格式不符合要求：" + testmsg,
          type: "warning",
        });
        return false;
      }
      return true;
    },

    uploadSectionFileSuggestion(params) {
      this.isUploadFinished = false;
      this.fileListLength += 1;

      const uid = params.file.uid;
      let keyname =
        formatDate(new Date(), "yyyyMMddhhmmss") +
        Math.floor(Math.random() * 1000);
      const fileData = new FormData();
      fileData.append("file", params.file);
      const query = {
        path:
          "/" +
          this.$store.state.projectInfo.projectName +
          "/施工配合/" +
          keyname +
          params.file.name,
      };

      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
          token: window.sessionStorage.getItem("token"),
        },
        // 这一段代码解决进度条不显示的问题，属于 axios 的使用知识。具体可以看文末的参考链接。
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.floor(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          params.onProgress({ percent: percentCompleted });
        },
      };

      httpfile.upload(query, config, fileData).then((res) => {
        console.log(res);
        if (res.status == 200) {
          this.fileListSuggestion4api.push({
            url: query.path,
            name: keyname + params.file.name,
          });
          params.onSuccess(res);
          console.log(this.fileListLength);
          console.log(this.fileListSuggestion4api.length);

          if (this.fileListLength === this.fileListSuggestion4api.length) {
            console.log("炒鸡成功");
            this.isUploadFinished = true;
          } else {
            console.log("普通成功");
            this.isUploadFinished = false;
          }
        }
      });
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleExceed(files, fileList) {
      this.$message.warning("最多选择 5 个文件");
    },

    //修改项目名称
    changeProjectName(value) {
      this.dictData.prolist.forEach((item) => {
        if (item.projectName === value) {
          console.log(item);
          this.flowFormData.projectId = item.projectId;
          return;
        }
      });
    },
  },

  computed: {},
};
</script>



<style lang='less' scoped>
.col-flex {
  box-sizing: border-box;
  padding-top: 30px;
  height: 100%;

  .breadcrumb-container {
    height: 30px;
    margin-top: -20px;
  }

  .maincont-container {
    height: 100%;
    margin-top: 3px;
    .table-container {
      height: 100%;
    }
    .flow-container {
      height: 100%;
      width: 100%;
      box-sizing: border-box;

      .flow-form {
        text-align: center;
        height: calc(~"100% - 10px");
        // height: 100%;

        table .form-label {
          background-color: #efefef;
        }

        .form-title {
          margin: 10px !important;
        }

        .form-data {
          border-collapse: collapse;
          margin: auto;
          width: 70%;
          font-size: 13px;
        }
        .btns {
          width: 70%;
          margin: 20px auto;
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }

  .scrollable {
    overflow: auto;
  }

  /deep/.el-form-item {
    padding: 0px;
    margin: 0px;
    .el-form-item__content {
      line-height: normal;
    }
    .el-select {
      display: block;
    }
  }

  /deep/.addbutton-con {
    button {
      box-shadow: 0px 0px 0px 3px #66b1ff55;
    }
    i {
      font-size: 20px;
    }
    z-index: 100;
    position: absolute;
    top: 10px;
    right: 10px;
    margin: 5px;
    height: 40px;
    border-radius: 50%;
    // box-shadow: 0px 0px 0px 2px gray;
  }
}
</style>